package com.hill;

public class ArrayRare {
    public static void main(String[] args) {
        //creat a array ull of many of 0
        int[][] array1=new int[12][12];
        array1[1][1] =1;
        array1[2][3]=5;
        array1[3][5]=8;
        System.out.println("输出数组");
        for(int[] ints:array1){
            for(int anint :ints)
                System.out.print(anint+"\t");
            System.out.println();
        }
        //创建稀疏数组
        int sum=0;
        for (int i=0;i<12;i++){
            for (int j=0;j<12;j++){
                if( array1[i][j]!=0){
                    sum++;
                }
            }
        }
        System.out.println("有效数值的个数为："+sum);
        int[][] arrary2 =new int[sum+1][3];
        arrary2[0][0]=12;
        arrary2[0][1]=12;
        arrary2[0][2]=sum;
        //遍历二维数组，存放稀疏数组中
        int count =0;
        for (int i=0;i<array1.length;i++){
            for (int j=0;j<array1.length;j++){
                if(array1[i][j]!=0){
                    count++;
                    arrary2[count][0]=i;
                    arrary2[count][1]=j;
                    arrary2[count][2]=array1[i][j];
                }
            }
        }
        //输出稀疏数组
        System.out.println("变为稀疏数组后：");
      for (int i=0;i<arrary2.length;i++){
          System.out.println(arrary2[i][0]+"\t"+arrary2[i][1]+"\t"+arrary2[i][2]);
      }

      //还原稀疏数组
        int[][] array3 = new int[arrary2[0][0]][arrary2[0][1]];
        for (int i=1;i<arrary2.length;i++){
            array3[arrary2[i][0]][arrary2[i][1]]=arrary2[i][2];
        }
        for(int[] ints:array3){
            for(int anint :ints)
                System.out.print(anint+"\t");
            System.out.println();
        }
    }

}
